package com.changgou.oauth.service.impl;

import com.changgou.oauth.service.UserLoginService;
import com.changgou.oauth.util.AuthToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Base64;
import java.util.Map;

/**
 * @author 戴金华
 * @date 2019-12-12 11:10
 */
@Service
public class UserLoginServiceImpl implements UserLoginService {

    //实现请求发送
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    /**
     * 用户登录验证(密码模式)
     * @param username
     * @param password
     * @param clientId
     * @param clientSecret
     * @param grant_type
     */
    @Override
    public AuthToken login(String username, String password, String clientId, String clientSecret, String grant_type) throws Exception {

        //获取指定服务的注册数据
        ServiceInstance serviceInstance = loadBalancerClient.choose("user-auth");
//        //调用请求地址
        String url = serviceInstance.getUri()+"/oauth/token";
//          String url = "http://localhost:9200/oauth/token";


        //请求提交的数据分装
        MultiValueMap<String,String> paramMap = new LinkedMultiValueMap<>();
        paramMap.add("username",username);
        paramMap.add("password",password);
        paramMap.add("grant_type",grant_type);

        //请求头封装
        String authorization = "Basic "+ new String(Base64.getEncoder().encode((clientId+":"+clientSecret).getBytes()),"UTF-8");
        MultiValueMap<String,String> headerMap = new LinkedMultiValueMap();
        headerMap.add("Authorization",authorization);

        //创建HttpEntity->创建该对象 分装请求头和请求体
        HttpEntity httpEntity = new HttpEntity(paramMap, headerMap);
        /**
         * 1.请求地址
         * 2.请求方式
         * 3.请求提交的数据信息分装  请求体&&请求头
         * 4，返回数据需要转换的类型
         */
        ResponseEntity<Map> responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Map.class);
        Map<String,String> map = responseEntity.getBody();
        System.out.println(map);
        AuthToken authToken = new AuthToken();
        authToken.setAccessToken(map.get("access_token").toString());
        authToken.setRefreshToken(map.get("refresh_token").toString());
        authToken.setJti(map.get("jti").toString());
        return authToken;
    }
}
